package y.q.h.util;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Map;

/**
 * @description:
 * @author: yifan
 * @date: 2022-03-26 14:22
 */
public class JavaWebToken {

    //jwt密钥 必须大于32个字符
    private static String TOKEN_KEY = "54f12048-1f56-45c1-a3f1-2c546bc2bb42";
    //jwt有效时间
    private static long TOKEN_TIMEOUT = 24 * 60 * 60 * 1000;

    private static Logger log = LoggerFactory.getLogger(JavaWebToken.class);

             //该方法使用HS256算法和Secret:bankgl生成signKey
             private static Key getKeyInstance() {
               //We will sign our JavaWebToken with our ApiKey secret
                 SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
                 byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(TOKEN_KEY);
                Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
                 return signingKey;
             }

             //使用HS256签名算法和生成的signingKey最终的Token,claims中是有效载荷
             public static String createJavaWebToken(Map<String, Object> claims) {
                 return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS256, getKeyInstance()).compact();
             }

             //解析Token，同时也能验证Token，当验证失败返回null
             public static Map<String, Object> parserJavaWebToken(String jwt) {
                 try {
                         Map<String, Object> jwtClaims = Jwts
                                 .parser()
                                 .setSigningKey(getKeyInstance())
                                 .parseClaimsJws(jwt)
                                 .getBody();
                         return jwtClaims;
                     } catch (Exception e) {
                         log.error("json web token verify failed");
                         return null;
                     }
             }


 }
